package com.radioapp.liaoliaobao.app;

import android.app.ActivityManager;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.util.NetUtils;
import com.jaydenxiao.common.baseapp.BaseApplication;
import com.previewlibrary.ZoomMediaLoader;
import com.radioapp.liaoliaobao.bean.lite.ChatUser;
import com.radioapp.liaoliaobao.receiver.MyEMMessageListener;
import com.radioapp.liaoliaobao.utils.AssetsUtils;
import com.radioapp.liaoliaobao.utils.LinNotify;

import org.litepal.LitePal;

import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import me.jessyan.autosize.utils.LogUtils;

/**
 * 功能：
 * 描述
 * Created by yue on 2019-06-27
 */
public class App extends BaseApplication {
    private static App mInstance;

    private static LocationClient mLocationClient;
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

        initEaseUI();
        //初始化本地的json数据
        AssetsUtils.newInterface().init();
        //数据库初始化
        LitePal.initialize(this);

        ZoomMediaLoader.getInstance().init(new GlideImageLoader());

       //创建渠道
        LinNotify.setNotificationChannel(this);


        //初始化百度
        initBaiDu();

        //极光
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);


    }
    /**
     * 百度地图初始化
     */
    private void initBaiDu() {
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        SDKInitializer.initialize(this);
        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。

        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(new BaiDuLocationListener());
//通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();

        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(8000);//3分钟定位一次
        option.setIsNeedAddress(true);
//设置locationClientOption
        mLocationClient.setLocOption(option);
    }



    public static void startLocation() {
        mLocationClient.start();
    }

    public static void stopLocation() {
        mLocationClient.stop();
    }

    /**
     * 初始化环信
     */
    private void initEaseUI() {
        int pid = android.os.Process.myPid();

      /*  String processAppName = getAppName(pid);
// 如果APP启用了远程的service，此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
// 默认的app会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回

        if (processAppName == null || !processAppName.equalsIgnoreCase("com.easemob.chatuidemo")) {
            LogUtils.e("enter the service process!");

            //"com.easemob.chatuidemo"为demo的包名，换到自己项目中要改成自己包名

            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }*/

        //本来想自己用官方的初始化的， 看到有些参数是默认的， 就直接用easeUi中 ，
        EaseUI.getInstance().init(this, null,new MyEMMessageListener());
        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        // EMClient.getInstance().setDebugMode(true);
        //注册一个监听连接状态的listener
        // EMClient.getInstance().addConnectionListener(new MyConnectionListener());
        //自定义获取用户数据接口
        EaseUI.getInstance().setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {
            @Override
            public EaseUser getUser(String username) {
                LogUtils.e("userName--->" + username);
                if(!TextUtils.isEmpty(username)){
                    List<ChatUser> list = LitePal.findAll(ChatUser.class);
                    if (list != null && list.size() > 0) {
                        for (ChatUser user : list) {
                            if (user.getUserId() == Integer.parseInt(username)) {
                                EaseUser easeUser = new EaseUser(username);
                                easeUser.setAvatar(user.getAvatar());
                                easeUser.setNickname(user.getNickName());
                                return easeUser;
                            }
                        }
                    }
                }

                return new EaseUser(username);
            }
        });


    }


    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            if (error == EMError.USER_REMOVED) {
                // 显示帐号已经被移除
            } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                // 显示帐号在其他设备登录
            } else {
                if (NetUtils.hasNetwork(mInstance)) {

                }
                //连接不到聊天服务器
                else {
                    //当前网络不可用，请检查网络设置
                }

            }
        }
    }


    private String getAppName(int pID) {
        String processName = "";
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    //Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ info.processName +"  Label: "+c.toString());
                    //processName = c.toString();
                    processName = info.processName;
                }
            } catch (Exception e) {
                //Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }


    public static App getInstance() {
        return mInstance;
    }
}
